import React, { useState, useEffect } from 'react';
import { useHistory } from "react-router-dom";
import http from '../../../../model/http';
import code from "../../../../model/code";
import './result.less';

import { SearchBar, Toast, Tabs, WingBlank, Drawer, Modal, Stepper, Accordion } from 'antd-mobile';
import Header from '../../../../components/header/Header'

function BillingSearchResult() {
    const history = useHistory();
    const [moduleShow, setModuleShow] = useState(false)
    // 暂存的数据
    const [cartLocalData, setCartLocalData] = useState([])
    const [cartLocalDataID, setCartLocalDataID] = useState([])

    // 获取到的数据 
    const [dataList, setDataList] = useState([])
    // tabs 点击的数据
    const [listData, setListData] = useState([])

    // 上面标签导航的数据
    const [labelData, setLabelData] = useState([{ name: '请选择' }])

    // 活动的项目数据
    const [listData2, setListData2] = useState([])

    // 请求接口
    const getDataFunc = async (v, t) => {
        const projectList = await http.get('/goods/searchlist', {
            search_content: v,
            type: t
        })
        if (history.location.state.btnType == 1 || history.location.state.btnType == 2) {
            let newData = projectList.data.map((item, index) => {
                return {
                    title: item.name,
                    deptId: item.deptId,
                    counts: item.counts,
                    subdata: item.subdata,
                }
            })
            setDataList(newData)
            setListData(newData[0].subdata)
        } else {
            setDataList(projectList.data)
        }


    }
    useEffect(async () => {
        // console.log(history.location.state.searchVal)

        getDataFunc(history.location.state.searchVal, history.location.state.btnType)

        let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
        setCartLocalData(localData)

        let localDataID = localStorage.getItem('billingCartDataID') ? JSON.parse(localStorage.getItem('billingCartDataID')) : []
        setCartLocalDataID(localDataID)
    }, [])
    

    // 点击tabs
    const tabsClick = (v) => {
        console.log(v)
        setListData(v.subdata)
    }


    // 点击已选择的项目 跳出弹框 
    const cartListClick = () => {
        setModuleShow(true)
        document.body.addEventListener("touchmove", window.scroll, { passive: false });
        document.body.style.overflow = 'hidden';
    }
    // 右边弹框
    const onOpenChange = () => {
        setModuleShow(!moduleShow)
        // 弹框关闭的时候 恢复body 滚动条
        if (moduleShow == true) {
            //添加事件监听时添加了passive参数，在ios9中移除事件监听也需要加此参数
            document.body.removeEventListener('touchmove', window.scroll, { passive: true });
            document.body.style.overflow = 'auto';
        }
    }
    // 点击项目
    const projectClickCard = (e, item) => {
        e.stopPropagation()
        item.strpperCount = 1
        item.itemType = history.location.state.btnType
        let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
        if (localData.length > 0) {
            let findItem = localData.find((elem, index) => {
                return elem.id == item.id
            })
            if (findItem == undefined) {
                localData.push(item)
            } else {
                // 重复点击的时候 移除当前数据
                let saveLocalData = localData
                localData = saveLocalData.filter(items => {
                    return items.id != item.id
                })
            }
        } else {
            localData.push(item)
        }
        localStorage.setItem('billingCartData', JSON.stringify(localData))
        setCartLocalData(localData)

        // 存一下 id 进行判断
        let localDataID = []
        localData.map(item => {
            localDataID.push(item.id)
        })
        localStorage.setItem('billingCartDataID', JSON.stringify(localDataID))
        setCartLocalDataID(localDataID)

    }
    // 重置购物车
    const allRemoveCart = () => {
        Modal.alert('提示', '是否确认重置购物车', [
            { text: '取消' },
            {
                text: '确认', onPress: async () => {
                    localStorage.removeItem('billingCartData')
                    localStorage.removeItem('billingCartDataID')
                    setCartLocalData([])
                    setCartLocalDataID([])
                    setModuleShow(false)
                }
            }
        ])
    }
    // 购物车移除单条数据
    const oneRemoveCart = (data) => {
        let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
        let newLocalData = localData.filter(item => {
            return item.id != data.id
        })
        localStorage.setItem('billingCartData', JSON.stringify(newLocalData))
        setCartLocalData(newLocalData)

        // 重新赋值暂存id
        let localDataID = []
        newLocalData.map(item => {
            localDataID.push(item.id)
        })
        localStorage.setItem('billingCartDataID', JSON.stringify(localDataID))
        setCartLocalDataID(localDataID)

        if(newLocalData.length < 1){
            setModuleShow(false)
        }
    }

    // 购物车增加数量跟减少数量
    const stepperCartChange = (e, data) => {
        console.log(data)
        console.log(e)
        if (e > 10) {
            e = 10
        }
        if (e <= 10 && e >= 0) {
            let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
            localData.map(item => {
                if (item.id == data.id) {
                    item.strpperCount = e
                }
            })
            localStorage.setItem('billingCartData', JSON.stringify(localData))
            setCartLocalData(localData)
        } else if (e == 0) {
            oneRemoveCart(data)
        }
    }

    // 点击label 的时候
    const removeLabel = (item, idx) => {
        if (history.location.state.btnType == '4') {
            if (item.tb_activity_id != undefined) {
                setLabelData([{ name: '请选择' }])
                getDataFunc2()
            }
        }

    }
    // 活动的标签请求
    const getDataFunc2 = async () => {
        setListData2([])
        const projectData = await http.get('/goods/getActivityClasssify')
        if (projectData.code == 0) {
            setDataList(projectData.data)
        } else {
            Toast.fail(projectData.msg)
        }
    }

    // 点击活动的请求接口 项目
    const getDataFunc3 = async (typeId) => {
        setDataList([])
        const projectData = await http.get('/goods/getActivityList', {
            activity_id: typeId
        })
        if (projectData.code == 0) {
            setListData2(projectData.data)
        } else {
            Toast.fail(projectData.msg)
        }
    }

    // 点击标签
    const typelistClick = (item) => {
        console.log(item)

        item.name = item.activity_name
        getDataFunc3(item.tb_activity_id)

        let newData = labelData.slice(0, -1)
        setLabelData([...newData, item, { name: '请选择' }])
    }

    // 去开单
    const onSubmitGo = () => {
        console.log('111')
        history.push('/billingPage')
        setModuleShow(false)
        document.body.removeEventListener('touchmove', window.scroll, { passive: true });
        document.body.style.overflow = 'auto';
    }
    return (
        <div className="v-billing-result">
            {/* <SearchBar placeholder="请输入要搜索的内容" onSubmit={(v) => searchClick(v)} /> */}
            <div className="billing-search-content">
                {history.location.state.btnType == '1' || history.location.state.btnType == '2' ?
                    <div className="search-result-tabs">
                        <Tabs tabs={dataList} onTabClick={(v) => tabsClick(v)} renderTabBar={props => <Tabs.DefaultTabBar {...props} page={3} />}>
                            <div>
                                <div><WingBlank className="project-nav-title">选择开单项目</WingBlank></div>

                                <div className="project-content-list2">
                                    {history.location.state.btnType == '1' ?
                                        <ul>
                                            {/* 项目跟产品 */}
                                            {listData.map((item, index) => (
                                                <li onClick={(e) => projectClickCard(e, item)} className={cartLocalDataID.includes(item.id) ? 'project-list-active' : ''}>
                                                    <div className="header-title">
                                                        {item.name}
                                                    </div>

                                                    <div className="content">
                                                        <span className="color-style"></span>
                                                        <p>{item.type_name}</p>
                                                        <p>原价:{item.price}元</p>
                                                        <p>次数:{item.use_times ? item.use_times : 0}次</p>
                                                        {cartLocalDataID.includes(item.id) ? '' : <i className="iconfont icon-zengjia"></i>}
                                                    </div>
                                                    <div className="footer">红线价格:{item.min_price}元</div>
                                                    {cartLocalDataID.includes(item.id) ?
                                                        <span className="sanjiaoxing">
                                                            <i className="iconfont icon-dagou"></i>
                                                        </span> : ''}
                                                </li>
                                            ))}
                                        </ul>
                                        : ''}
                                    {history.location.state.btnType == '2' ?
                                        <ul>
                                            {/* 项目跟产品 */}
                                            {listData.map((item, index) => (
                                                <li onClick={(e) => projectClickCard(e, item)} className={cartLocalDataID.includes(item.id) ? 'project-list-active' : ''}>
                                                    <div className="header-title">
                                                        {item.name}
                                                    </div>

                                                    <div className="content">
                                                        <span className="color-style"></span>
                                                        <p>{item.type_name}</p>
                                                        <p>{item.spec}/{item.basic_unit}</p>
                                                        {cartLocalDataID.includes(item.id) ? '' : <i className="iconfont icon-zengjia"></i>}
                                                    </div>
                                                    <div className="footer">价格:{item.price}元</div>
                                                    {cartLocalDataID.includes(item.id) ?
                                                        <span className="sanjiaoxing">
                                                            <i className="iconfont icon-dagou"></i>
                                                        </span> : ''}
                                                </li>
                                            ))}



                                        </ul>
                                        : ''}
                                </div>
                            </div>

                        </Tabs>
                    </div> : ''}


                {history.location.state.btnType == '3' ?
                    <div>
                        <div><WingBlank className="project-nav-title">选择开单项目</WingBlank></div>
                        <div className="project-content" style={{ height: 'calc(100vh - 94px)' }}>
                            <div className="package-list-box">
                                {/* 套餐 */}
                                {dataList.map((item, index) => (

                                    <Accordion className={cartLocalDataID.includes(item.id) ? 'my-accordion-avtive' : 'my-accordion'} >
                                        <Accordion.Panel header={
                                            <div className="small-box">
                                                <div className="header">
                                                    <b>{index + 1}</b><p>{item.name}</p>
                                                </div>
                                                <div className="center">
                                                    <span>价格:{item.price}</span>
                                                    <p>{item.begin_date} ~ {item.end_date}</p>
                                                    {cartLocalDataID.includes(item.id) ? '' : <span className="iconfont icon-zengjia" onClick={(e) => projectClickCard(e, item)}></span>}
                                                </div>
                                                {cartLocalDataID.includes(item.id) ?
                                                    <span className="sanjiaoxing" onClick={(e) => projectClickCard(e, item)}>
                                                        <span className="iconfont icon-dagou"></span>
                                                    </span> : ''}
                                            </div>
                                        }>
                                            <ul className="package-list-box-ul">
                                                {item.subdata.map((data, index) => (
                                                    <li>
                                                        <div className="header-title">
                                                            {data.type_name}名称:{data.item_name}
                                                        </div>

                                                        <div className="content">
                                                            <span className="color-style"></span>
                                                            <p>{data.dgname}</p>
                                                            <p>原价:{data.original_price}元</p>
                                                            {data.type == '1' ? <p>次数:{data.use_times ? data.use_times : 0}次</p>
                                                                : <p>{data.unit}{data.spec}</p>}

                                                        </div>
                                                        <div className="footer">套餐价:{data.amt}元</div>
                                                    </li>
                                                ))}
                                            </ul>

                                        </Accordion.Panel>

                                    </Accordion>

                                ))}
                            </div>

                        </div>
                    </div>

                    : ''}

                {history.location.state.btnType == '4' ?
                    <div>
                        <div><WingBlank className="project-nav-title">已选择</WingBlank></div>
                        <div className="project-click-list">
                            <ul>
                                {labelData.map((item, index) => (
                                    <li onClick={() => removeLabel(item, index)}><span>{item.name}</span></li>
                                ))}
                            </ul>
                        </div>
                        <div><WingBlank className="project-nav-title">选择开单项目</WingBlank></div>
                        <div className="project-content">
                            <ul>
                                {/* 套餐跟活动 */}
                                {dataList.map((item, index) => (
                                    <li
                                        onClick={() => typelistClick(item)}
                                        className="box-package">
                                        <div className="package-header-box">
                                            <p>{item.activity_name}</p>
                                            <span className="iconfont icon-youjiantou1"></span>
                                        </div>
                                        <div className="package-footer-box">
                                            <p>{item.begin_date} ~ {item.end_date}</p>
                                        </div>
                                    </li>
                                ))}
                            </ul>
                            <div className="project-content-list">
                                <ul>
                                    {/* 活动 */}
                                    {listData2.map((item, index) => (
                                        <li onClick={(e) => projectClickCard(e, item)} className={cartLocalDataID.includes(item.id) ? 'project-list-active' : ''}>
                                            <div className="header-title">
                                                {item.type_name}名称:{item.name}
                                            </div>

                                            <div className="content">
                                                <span className="color-style"></span>
                                                <p>{item.dgname}</p>
                                                <p>原价:{item.original_price}元</p>
                                                {item.type == '1' ? <p>次数:{item.use_times ? item.use_times : 0}次</p>
                                                    : <p>{item.unit}{item.spec}</p>}
                                                {cartLocalDataID.includes(item.id) ? '' : <i className="iconfont icon-zengjia"></i>}
                                            </div>
                                            <div className="footer">活动价:{item.activity_price}元</div>
                                            {cartLocalDataID.includes(item.id) ?
                                                <span className="sanjiaoxing">
                                                    <i className="iconfont icon-dagou"></i>
                                                </span> : ''}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        </div>

                    </div>

                    : ''}

            </div>





            <div className={cartLocalData.length > 0? 'project-shop-cart':'project-shop-cart cart-box-no-data'}>
                <div className="left" onClick={() => cartLocalData.length > 0?cartListClick():''}>
                    <span className="iconfont icon-wodedingdan2"></span>
                    <div className="left-sign">
                        <p>{cartLocalData.length}</p>
                    </div>
                </div>
                <div className="center" onClick={() => cartLocalData.length > 0?cartListClick():''}>
                    <p>已选择 {cartLocalData.length} 个开单项目</p>
                </div>
                <div className="right" onClick={() => onSubmitGo()}>
                    <p>去开单</p>
                </div>
            </div>
 

            {/* 购物车 */}
            {moduleShow ? <Drawer
                className="my-drawer"
                style={{ position: 'fixed' }}
                position='bottom'
                enableDragHandle
                contentStyle={{ color: '#A6A6A6', textAlign: 'center', paddingTop: 42 }}
                sidebar={
                    <div className="project-drawer-box">
                        <div className="box-header">
                            <b></b><p>已经选择的开单项目</p>
                            <span onClick={() => allRemoveCart()}>重置</span>
                        </div>
                        <div className="box-content">
                            <ul>
                                {cartLocalData.map((item, index) => (
                                    <li>
                                        <p>
                                            {item.itemType == '1'?<b style={{color:'#2b4490'}}>[项目]</b>:(item.itemType == '2'?<b style={{color:'#007d65'}}>[产品]</b>:(item.itemType == '3'?<b style={{color:'#f47920'}}>[套餐]</b>:<b style={{color:'#e73746'}}>[活动]</b>))}
                                            &nbsp;{item.name}
                                        </p>
                                        <Stepper
                                            style={{ width: '80px', marginLeft: '20px', marginRight: '15px' }}
                                            showNumber
                                            max={10}
                                            min={1}
                                            value={item.strpperCount}
                                            onChange={(e) => stepperCartChange(e, item)}
                                        />
                                        <span className='iconfont icon-cuo' onClick={() => oneRemoveCart(item)}></span>


                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                }
                open={moduleShow}
                onOpenChange={() => onOpenChange()}
            >
            </Drawer> : ''}

            <Header />
        </div>
    )
}
export default BillingSearchResult;